#include "WRR_Scheduler.h"

/* This function implements the logic of WRR Scheduler,
	According to WRR each Flow has it's own weight dictated on first packet of the flow,
	the scheduler let each flow send "weight" amount of packets when it's scheduled.

	steps:
	1. store current flow weight at wgt.
	2. while there is a packet and we haven't scheduled "weight" packets already(wgt > 0):
	2.1. Take out first packet from current flow's head packets queue
	2.2. Write to the output file the result
	2.3. Advance the current_time (to the time after this packet was sent).
	2.4. Load from input file all the new packets that arrived to the system 
	until that time (if not reached to the end of file yet).
	2.5. reduce wgt by one packet

	On success this function return 0, and on fail return 1.
*/

int WRR_Scheduler::ScheduleCurrentFlow()
{
	unsigned short int wgt = current_flow->getWeight();
	while (wgt && current_flow->Get1PacketLength()) // while flow's queue is not empty and there is still rounds to do
	{
		long int return_time = current_flow->Remove_Pkt_From_Flow(current_time, outfile_p);
		if (return_time == -1)
		{
			cerr << "Failed to remove packet from flow.\n";
			return 1;
		}
		else
		{
			current_time = return_time;
			if (!end_of_input)
			{
				if (Load_data_to_Schedule())
				{
					cerr << "Failed to load data from file.\n";
					return 1;
				}
			}
		}
		wgt--;
	}
	return 0;
}